package com.chuangke.login.controller;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import com.chuangke.admin.dto.RegisterBean;
import com.chuangke.admin.service.SysUserService;
import com.chuangke.common.http.HttpResult;
import com.chuangke.login.dto.LoginBean;
import com.chuangke.login.service.SysLoginService;
import com.chuangke.system.annotation.OptLogDoc;
import com.chuangke.system.enums.LogBisType;
import com.chuangke.system.enums.LogOptType;

/**
 * 登录控制器
 *
 * @author chuangke
 * @date Oct 29, 2018
 */
@RestController
public class SysLoginController {

    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysLoginService sysLoginService;

    /**
     * 验证码
     * @param response
     * @param request
     * @throws IOException
     */
    @GetMapping("captcha.jpg")
    public void captcha(HttpServletResponse response, HttpServletRequest request) throws IOException {
        // 生成验证码
        sysLoginService.captcha(response, request);
    }

    /**
     * 登录接口
     */
    @OptLogDoc(objId = "data['userId']", name = "登录了系统", optType = LogOptType.LOGIN, objType = LogBisType.auth)
    @PostMapping(value = "/login")
    public HttpResult login(@RequestBody LoginBean loginBean, HttpServletRequest request) {
        //登录
        return HttpResult.ok(sysLoginService.login(loginBean, request));
    }

    /**
     * 退出接口
     */
    @GetMapping(value = "/signout")
    public HttpResult logout(HttpServletRequest request) {
        sysLoginService.logout(request);
        return HttpResult.ok();
    }

    /**
     * 注册接口
     */
    @PostMapping(value = "/register")
    public HttpResult register(@RequestBody @Validated RegisterBean registerBean) {
        sysUserService.register(registerBean);
        return HttpResult.ok();
    }

    /**
     *获取移动端菜单
     */
    @GetMapping(value = "/getappmenu")
    @PreAuthorize("hasAuthority('login:action')")
    public HttpResult getAppMenu() {
        return HttpResult.ok(sysLoginService.getAppMenu());
    }

}